<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Go 笔记：Gob Write/Read File</title>
  
    <meta name="author" content="jouyouyun">

    <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- Le styles -->
    <link href="/assets/twitter/stylesheets/bootstrap.min.css" type="text/css" rel="stylesheet" media="all">
<link href="/assets/twitter/stylesheets/style.css" type="text/css" rel="stylesheet" media="all">
<link href="/assets/twitter/widgets/google_prettify/stylesheets/twitter-bootstrap.css" type="text/css" rel="stylesheet" media="all">
 

    <!-- Le fav and touch icons -->
  <!-- Update these with your own images
    <link rel="shortcut icon" href="images/favicon.ico">
    <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
  -->
  </head>

  <body>

    <div class="navbar">
      <div class="navbar-inner">
        <div class="container">
          <a class="brand" href="/">Jouyouyun&#39;s Blog</a>
          <ul class="nav">
            
              


  <li><a href="/archive">Archive</a></li>


            
              


  <li><a href="/tags">Tags</a></li>


            
              


  <li><a href="/categories">Categories</a></li>


            
              


  <li><a href="/about">About Me</a></li>


            
          </ul>
        </div>
      </div>
    </div>

    <div class="container">

      <div class="content">
        <div class="page-header">
  <h1>Go 笔记：Gob Write/Read File </h1>
</div>

<div class="row">
  <div class="span8">
    <p><code>Gob</code> 使用实例，将结构体写入文件里，在需要的时候再从文件中读取出来。</p>

<pre><code class="language-go">package main

import (
	&quot;bytes&quot;
	&quot;encoding/gob&quot;
	&quot;fmt&quot;
	&quot;io/ioutil&quot;
	&quot;os&quot;
)

type Writer struct {
	Id    int
	Name  string
	Value string
}

type Reader struct {
	Name  string
	Value string
}

func writeToFile(filename string, data interface{}) bool {
	if len(filename) &lt; 1 {
		fmt.Println(&quot;writeToFile filename invalid&quot;)
		return false
	}

	var w bytes.Buffer

	enc := gob.NewEncoder(&amp;w)
	if err := enc.Encode(data); err != nil {
		fmt.Printf(&quot;Encode data error: %v\n&quot;, err)
		return false
	}

	if fp, err := os.Create(filename); err != nil {
		fmt.Printf(&quot;Open '%s' error: %v\n&quot;, filename, err)
		return false
	} else {
		defer fp.Close()
		fp.WriteString(w.String())
		fp.Sync()
	}

	return true
}

func readFromFile(filename string, data interface{}) {
	if len(filename) &lt; 1 || data == nil {
		fmt.Println(&quot;readFromFile args invalid&quot;)
		return
	}

	contents, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Printf(&quot;ReadFile '%s' error: %v\n&quot;, filename, err)
		return
	}

	r := bytes.NewBuffer(contents)
	dec := gob.NewDecoder(r)

	if err := dec.Decode(data); err != nil {
		fmt.Printf(&quot;Decode error: %v\n&quot;, err)
		return
	}

	return
}

func main() {
	wData := Writer{0, &quot;firefox&quot;, &quot;Web Broswer&quot;}

	writeToFile(&quot;/tmp/w&quot;, &amp;wData)

	rData := Reader{}
	readFromFile(&quot;/tmp/w&quot;, &amp;rData)
	fmt.Printf(&quot;%v\n&quot;, rData)

	// test map
	w := map[string]string{
		&quot;sublime-text&quot;: &quot;Sublime Text&quot;,
		&quot;firefox&quot;:      &quot;Web Broswer&quot;,
		&quot;terminator&quot;:   &quot;Terminator&quot;,
	}
	writeToFile(&quot;/tmp/map&quot;, &amp;w)
	r := make(map[string]string)
	readFromFile(&quot;/tmp/map&quot;, &amp;r)
	fmt.Printf(&quot;%v\n&quot;, r)
}
</code></pre>

    <hr>
    <div class="pagination">
      <ul>
        <ul>
          
            <li class="prev"><a href="/Note/Go-%E7%AC%94%E8%AE%B0--%E7%AE%80%E5%8D%95%E7%9A%84-TCP-Socket-%E7%A4%BA%E4%BE%8B/" title="Go 笔记: 简单的 TCP Socket 示例">&larr; Previous</a></li>
          
          

            <li><a href="/archive">Archive</a></li>

          
            <li class="next"><a href="/Blog/chroot-%E8%84%9A%E6%9C%AC/" title="chroot 脚本">Next &rarr;</a></li>
          
          
        </ul>
      </ul>
    </div>
    <hr>
    
<div id="disqus_thread"></div>
<script>
    var disqus_developer = 1;
    var disqus_shortname = 'jekyllbootstrap'; // required: replace example with your forum shortname
    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>

  </div>
  
  <div class="span4">
    <h4>Published</h4>
    <div class="date"><span>2014-07-07 13:06:28</span></div>
    <br>
    <h4>Categories</h4>
    <ul class="tag_box">
    
      <li>
  <a href="/categories/#Note-ref">Note <span>9</span></a>
</li>
    
    </ul>
    <br>
    <h4>Tags</h4>
    <ul class="tag_box">
    
      <li>
  <a href="/tags/#go-ref">go <span>6</span></a>
</li>
    
      <li>
  <a href="/tags/#gob-ref">gob <span>2</span></a>
</li>
    
    </ul>
  </div>
</div>

      </div>

      <footer>
        <p>&copy; jouyouyun 2013 
          with help from <a href="http://github.com/wendal/gor" target="_blank" title="Gor -- Fast Blog">Gor</a>
          and <a href="http://twitter.github.com/bootstrap/" target="_blank">Twitter Bootstrap</a>
		  and Idea from <a href="http://ruhoh.com" target="_blank" title="The Definitive Technical Blogging Framework">ruhoh</a>
        </p>
      </footer>

    </div> <!-- /container -->

    
<script src="//cdnjscn.b0.upaiyun.com/libs/prettify/r298/prettify.min.js"></script>
<script>
  var pres = document.getElementsByTagName("pre");
  for (var i=0; i < pres.length; ++i) {
    pres[i].className = "prettyprint linenums";
  }
  prettyPrint();
</script>

    
<script type="text/javascript">

  var _gaq = _gaq || [];
  var pluginUrl = '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
  _gaq.push(['_require', 'inpage_linkid', pluginUrl]);
  _gaq.push(['_setAccount', 'UA-123-12']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
  </body>
</html>
